package pwr.online.cow;

import java.awt.BorderLayout;
import java.util.Random;

import javax.swing.JFrame;
import javax.swing.JPanel;

import pwr.online.cow.model.Board;
import pwr.online.cow.model.Position;
import pwr.online.cow.model.Position1D;
import pwr.online.cow.model.Position2D;

public class Main implements BoardControllerListener {

	private CowSearchAlgorithm mCSA;
	private Board mBoard;
	static private boolean is1DActive = true;
	
	private void createAndShowGUI() {
		JFrame frame = new JFrame();
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

		JPanel p = new JPanel();

		mBoard = new Board();
		Random r = new Random();
		
		if (is1DActive) {
			Board1DView v = new Board1DView();
			mBoard.addListener(v);
			
			BoardContoller1D bc = new BoardContoller1D();

			mBoard.addListener(bc);
			bc.addListener(v);
			bc.addListener(this);
			
			Position cowPosition = new Position1D(r.nextInt(Board1DView.CELLS_HORIZONTAL));
			v.setCowPosition(cowPosition);
			
			mCSA = new CowSearchAlgorithm1D(mBoard, cowPosition);
			v.AddCowPositionUpdateListener(mCSA);
			bc.addListener((CowSearchAlgorithm1D)mCSA);

			p.add(v, BorderLayout.CENTER);
			p.add(bc, BorderLayout.CENTER);
		}
		else {
			Board2DView v = new Board2DView();
			mBoard.addListener(v);
			
			BoardContoller bc = new BoardContoller();

			mBoard.addListener(bc);
			bc.addListener(v);
			bc.addListener(this);
			
			Position cowPosition = new Position2D(r.nextInt(Board2DView.CELLS_HORIZONTAL), r.nextInt(Board2DView.CELLS_VERTICAL));
			v.setCowPosition(cowPosition);
			
			mCSA = new CowSearchAlgorithm2D(mBoard, cowPosition);
			v.AddCowPositionUpdateListener(mCSA);
			bc.addListener((CowSearchAlgorithm2D)mCSA);

			p.add(v, BorderLayout.CENTER);
			p.add(bc, BorderLayout.CENTER);
		}
		frame.add(p);
		frame.pack();
		frame.setVisible(true);
	}

	@Override
	public void HistoryViewChanged(int newValue) {}

	@Override
	public void RestartAlgorithm() {
		mBoard.clearBoard();
		mCSA.reset();
		for (int i = 0; i < 221; ++i)
			mCSA.doStep();

	}

	@Override
	public void NewStartDirection(int x, int y) {}
	

	public static void main(String[] args) {
		if (args.length > 0)
			is1DActive = !args[0].equals("2d");

		javax.swing.SwingUtilities.invokeLater(new Runnable() {
			@Override
			public void run() {
				Main main = new Main();
				main.createAndShowGUI();
			}
		});
	}
}
